package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.ruitaowang.core.utils.TimeUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

public class BinaryUploader {

    Logger logger = LogManager.getLogger("BinaryUploader");
    /**
     * create by neal.ma
     */
    public static final State save(HttpServletRequest request, Map<String, Object> conf) {
        boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
        String goodsId = request.getParameter("goodsId");
        String imageType = request.getParameter("imageType");
        String isActivity = request.getParameter("isActivity");
        if ((!StringUtils.hasLength(goodsId) || !StringUtils.hasLength(imageType)) && !StringUtils.hasLength(isActivity)) {
            return new BaseState(false, 5);
        }
        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, 5);
        }
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        if (isAjaxUpload) {
            upload.setHeaderEncoding("UTF-8");
        }
        try {
            String now = TimeUtils.getCurrentDatetime(TimeUtils.TimeFormat.LONG_DATE_PATTERN_DD);
//            String savePath = request.getServletContext().getRealPath("/") + "/attached/file/" + now + "/";
            String savePath = "/usr/local/static/img/" + now + "/";
            
//            String saveUrl = request.getContextPath() + "/attached/file/" + now + "/";
            String saveUrl =  request.getScheme()+"://"+request.getServerName() + "/img/" + now + "/";
            //上传附件目录
            Path path = Paths.get(savePath);
            if (!Files.isDirectory(path)) {
                try {
                    Files.createDirectories(path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //重新命名文件名字
            String newFileName = "", fileExt = "", fileName = "";
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {//将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator<String> it = multiRequest.getFileNames();
                //遍历文件
                while (it.hasNext()) {
                    MultipartFile file = multiRequest.getFile(it.next().toString());
                    if (file != null) {
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        fileName = file.getOriginalFilename();
                        fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                        //新文件名称
                        String salt = df.format(new Date()) + "_" + new Random().nextInt(1000);
                        newFileName = savePath + salt + fileExt;
                        saveUrl = saveUrl + salt + fileExt;
                        if (!validType(fileExt, (String[]) conf.get("allowFiles"))) {
                            return new BaseState(false, 8);
                        }
                        try {
                            //上传文件
                            file.transferTo(new File(newFileName));
                        } catch (IllegalStateException | IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            State storageState = new BaseState(Boolean.TRUE);
            if (storageState.isSuccess()) {
                storageState.putInfo("url", PathFormat.format(saveUrl));
                storageState.putInfo("type", fileExt);
                storageState.putInfo("original", fileName);
                storageState.putInfo("goodsId", goodsId);
                storageState.putInfo("imageType", imageType);

                //TODO:storage to db

            }
            return storageState;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new BaseState(false, 4);
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);
        return list.contains(type);
    }
}
